import json

from firstDjango.decorators import dump_form_data, post, get
from firstDjango.exceptions import FormException
from index.models import UserInfo
from index.protocol.user_protocol import UpdateUserInfo, GetUserInfoResponse, ModifyPasswordRequest, \
    VerifyPasswordRequest
from index.service import user_service
from django.core.handlers.wsgi import WSGIRequest
from django.http.response import JsonResponse


# 用户注册
def register(request: WSGIRequest) -> JsonResponse:
    # body = request.body
    # print(body)
    # user = json.loads(body)
    user = json.loads(request.body.decode('utf-8'))
    username = user.get("username")
    password = user.get("password")
    gender = user.get("gender")

    resp = user_service.create_user(username, password, gender)
    return JsonResponse(resp)


# 用户注销
def logoff(request: WSGIRequest):
    request.session.delete()
    return "注销成功"


# 用户登录
@dump_form_data
def login(request):
    user = getattr(request, 'form_data', {})
    username = user.get('username')
    password = user.get('password')
    user_info = user_service.login(username, password)
    request.session["user"] = user_info
    return "ok"


# 添加额外信息
def add_ExtendUserInfo(request: WSGIRequest) -> JsonResponse:
    extend_userInfo = json.loads(request.body.decode("utf-8"))
    user = request.session.get("user")
    user_id = user.id
    signature = extend_userInfo.get("signature")
    nickname = extend_userInfo.get("nickname")
    rsp = user_service.add_ExtendUserInfo(user_id, signature, nickname)
    return JsonResponse(rsp)


# 通过id获取用户信息
@get(response_data_class=GetUserInfoResponse)
def getUserInfo(request: WSGIRequest):
    user = request.session.get("user")
    user_id = user.id
    return user_service.getUserInfo(user_id)


# 更新用户信息
@post(request_data_class=UpdateUserInfo)
def updateUserInfo(request: WSGIRequest, update_info: UpdateUserInfo):
    user_id = request.session.get("user").id
    user_service.update_userInfo(user_id, update_info)
    return "ok"


def verification_password(user_id, password):
    user = UserInfo.objects.get(id=user_id)
    if user.password != password:
        raise FormException("密码不正确")
    return user


@post(request_data_class=ModifyPasswordRequest)
def modify_password(req: WSGIRequest, data: ModifyPasswordRequest):
    user_id = req.session.get("user").id
    try:
        user = verification_password(user_id, data.old_password)
    except FormException:
        raise FormException("原密码错误")
    user.password = data.new_password
    user.save()


@post(request_data_class=VerifyPasswordRequest)
def verify_password(req: WSGIRequest, data: VerifyPasswordRequest):
    user_id = req.session.get("user").id
    verification_password(user_id, data.password)
